﻿/*
 * Created by SharpDevelop.
 * User: StrunevskyDV
 * Date: 23.01.2010
 * Time: 9:39
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Threading;
using System.Timers;
using agsXMPP.protocol.client;
using agsXMPP.Xml.Dom;
using EmailJabber.EmailJabber.Core;
using EmailJabber.Logic.Commands.Base;
using Timer=System.Timers.Timer;
using agsXMPP;

namespace EmailJabber.Logic.Logic.Messengers.JabberMessenger
{
    /// <summary>
    /// Description of JabberClient.
    /// </summary>
    public sealed class JabberClient : IMessenger
    {
        private static XmppClientConnection Xmpp;
        private Jid jidSender;
        private string password;
        private const string RESOURCE_TEXT = "smpt{0}";
        private const string STATUS_FORMAT = "Reconected at {0}";
        private static DateTime lastOperation = DateTime.Now;

        public JabberClient(string userJid,string pass)
        {
            jidSender =new Jid(userJid);
            jidSender.Resource = string.Format(RESOURCE_TEXT, DateTime.Now.ToShortTimeString());
            password = pass;
            SetTimerJobs();
            InitXmpp();
            Reconnect();
        }
        public event EventHandler<MessageIM> MessageRecived;

        public CommandBase OnReciveMessageFromAdmin { get; set; }


       

        private void InitXmpp()
        {
            Xmpp = new XmppClientConnection(jidSender.Server);
            Xmpp.OnClose += XmppOnClose;
            Xmpp.OnMessage += XmppOnMessage;
            Xmpp.OnError += Xmpp_OnError;
            Xmpp.OnAuthError += Xmpp_OnAuthError;
        }

        void Xmpp_OnAuthError(object sender, Element e)
        {
        	Console.WriteLine("Error auth ");
        }

        void Xmpp_OnError(object sender, Exception ex)
        {
        	Console.WriteLine(ex);
        }

        private void Reconnect()
        {
            if (!Xmpp.Binded)
            {
                Xmpp.Open(jidSender.User, password, string.Format(RESOURCE_TEXT, DateTime.Now.ToShortTimeString()));
                Xmpp.KeepAlive = true;
                Xmpp.Status = string.Format(STATUS_FORMAT, DateTime.Now);
            }
        }

        private void XmppOnMessage(object sender, Message msg)
        {
            Message message = msg;
            MessageIM messageIM = new MessageIM(msg.From.Bare,message.Body,message.To.User);
            MessageRecived.Invoke(sender, messageIM);
        }

        private void XmppOnClose(object sender)
        {
            Reconnect();
        }

        private void SetTimerJobs()
        {
            Timer tmr = new Timer();
            tmr.Elapsed += OnTimedEvent;
            tmr.Interval = 60000;
            tmr.Enabled = true;
        }

        private void OnTimedEvent(object sender, ElapsedEventArgs e)
        {
            Reconnect();
        }

        public void Send(MessageIM message)
        {
            if ((lastOperation - DateTime.Now).TotalMilliseconds < 500)
            {
                Thread.Sleep(500);
            }
            Message mess = new Message(new Jid(message.To), MessageType.chat, message.Body);
            Xmpp.Send(mess);
            lastOperation = DateTime.Now;
        }

        
    }
}